package demo;

import java.util.concurrent.atomic.AtomicBoolean;

public class demo {
    private static final AtomicBoolean b = new AtomicBoolean(false);

    // private static final AtomicBoolean can = new AtomicBoolean(true);
    private static volatile boolean can = true;

    public static void main(String[] args) {
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
        new Task().start();
    }

    private static final class Task extends Thread {

        @Override
        public void run() {
            final Object lock = Task.class;
            synchronized (lock) {
                // while (!can.get()) {
                while (!can) {
                    try {
                        lock.wait(1000);
                    } catch (InterruptedException e) {

                    }
                }
                System.out.println(Thread.currentThread().getId());
                // can.set(false);
                can = false;
            }

            test();
            synchronized (lock) {
                // can.set(true);
                can = true;
                lock.notify();
            }
        }

        private void test() {
            if (b.compareAndSet(false, true)) {
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                b.compareAndSet(true, false);
            } else {
                System.err.println("并发了");
            }
        }
    }
}
